"use strict";
const tool = require("../utils/tool");
const lightAppDao = require("../dao/light_app_dao");
const request = require("request-promise-native");
const Constants = require("../config");
const mongoose = require("mongoose");

async function notifyMessageWithTemplate(req, res) {
  const client = tool.getResponseFunc(res);
  try {
    const reqQuery = req.query;
    const atworkParams = {
      orgId: Constants.orgId,
      domainId: Constants.domainId,
      clientId: reqQuery.agentid,
      clientSecret: reqQuery.agentSecret
    };
    if(!atworkParams.clientId || !atworkParams.clientSecret || !atworkParams.orgId){
      console.log(JSON.stringify(atworkParams));
      client.fail(new Error("参数错误"));
      return;
    }
    const users = req.body.touser.split("|");
    client.success({});
    for(let user of users){ //因为要加上单独的sso信息，所以每条用户发一条
      const atworkInstance = await tool.getAtworkInstance(atworkParams);
      const content = {
        usernames: [user],
        topColor: "#2a92fc",
        topAvatar: "",
        topTitle: "消息",
        platforms: ['IOS','ANDROID','PC'],
        '@target_alert': req.body.content,
        actions: [
          {
            "name": "查看详情",
            "value": "{{url.DATA}}"
          }
        ],
        title: req.body.content,
        data: [
          {
            key: "url",
            value: `${req.body.msgurl}?code=${user}`
          }
        ]
      }
      try{
        await atworkInstance.notifyWithTemplateMessageCtx(content);
      }catch(e){
        console.log(e);
        console.log('发送失败，进行清理');
        // status没传来，如果失败强制认为是模板被删除了，清空数据库记录，
        // 本次发送失败，下次会重新创建模板
        // const messageTemplate = mongoose.model("messageTemplate");
        // await messageTemplate.remove(orgInfo);
      }
    }
  } catch (e) {
    console.error(e);
  }
}

async function getLogoMediaId(atworkParams) {
  try {
    const logoModel = mongoose.model("logo");
    const results = await logoModel.findOne({domainId: atworkParams.domainId});
    if (results && results.mediaId) {
      return results.mediaId;
    } else {
      return await uploadingLogo(atworkParams)
    }
  } catch (e) {
    console.log(e);
  }
}

async function uploadingLogo(atworkParams) {
  const logoModel = mongoose.model("logo");
  const path = require("path");
  try {
    const logoFilePath = path.normalize(__dirname + "/..") + "/config/logo.png";
    const atworkInstance = await tool.getAtworkInstance(atworkParams);
    const results = await atworkInstance.uploadImage({path: logoFilePath});
    if (results && results.status == 0) {
      await logoModel.create({domainId: atworkParams.domainId, mediaId: results.result});
      return results.result;
    } else {
      return null;
    }

  } catch (e) {
    console.log(e);
  }
}

module.exports = {
  notifyMessageWithTemplate
}
